package cn.com.se.sharepictrue.presenter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.URLS;
import cn.com.se.sharepictrue.model.LoginModel;
import cn.com.se.sharepictrue.model.LoginModelImp;
import cn.com.se.sharepictrue.iview.LoginViewImp;
import cz.msebera.android.httpclient.Header;

/**
 * 登录presenter类
 * 对登录的view和model操作
 * Created by KIDNG on 2015/11/12.
 */
public class LoginPresenter {
    private LoginModelImp mLoginModel;
    private LoginViewImp mLoginView;
    private String PHONE_KEY = "userPhone";
    private String PASSWORD_KEY = "password";
    private int LOGIN_SUCCESS_STATUS = 1;

    public LoginPresenter(LoginViewImp loginView) {
        mLoginView = loginView;
        mLoginModel = new LoginModel();
    }

    public void saveUser(String phone,String password){
        mLoginModel.setPhone(phone);
        mLoginModel.setPassword(password);
    }
    public void login(String phone, String password){
        mLoginModel.setPhone(phone);
        mLoginModel.setPassword(password);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put(PHONE_KEY,phone);
        params.put(PASSWORD_KEY,password);
        PersistentCookieStore myCookieStore = new PersistentCookieStore(mLoginView.getContext());
        client.setCookieStore(myCookieStore);
        client.post(mLoginView.getContext(), URLS.login,params, new BaseJsonHttpResponseHandler<NetworkResponse<String>>() {
            @Override
            public void onStart() {
                super.onStart();
                mLoginView.LoginStart();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,NetworkResponse<String> response) {
                if(response.isStatus()){
                    mLoginView.LoginSuccess(response.getError());
                }else {
                    mLoginView.LoginFail(response.getError());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, NetworkResponse<String> errorResponse) {
                mLoginView.InternetError();
            }

            @Override
            protected NetworkResponse<String> parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                if(isFailure)
                    return null;
                else
                    return new Gson().fromJson(rawJsonData,new TypeToken<NetworkResponse<String>>(){}.getType());
            }
        });
    }
}
